﻿using HBase;
using HBase.db;
using hCommand;
using Net.http;
using System;
using System.Collections.Generic;
using System.Reflection.Emit;

namespace Persistence {
    public class PkFinshEngine : GkTransaction {
        public long pkId;


        protected override TransRes Execute() {

            WhDopk pk = getById<WhDopk>(pkId);
            if (pk.status != (int)DoStatus.执行中) {
                return new TransRes("盘库计划状态异常");
            } 
            String query = "Select d. * from  core_stock_det d join core_stock s  on d.pid=s.id where s.PK_ID=@pkId  and d.status in ({0},{1})";
            List<CoreStockDet> List = query<CoreStockDet>(HUtil.s(query, StockDetailStatus.盘亏中, StockDetailStatus.盘盈), new { pkId }); 

            string sql = "update core_stock_det set status={0} ,doo_Type={2},doo_Det_Id=@pkId,out_time=sgj_get_sys_now  where  pid in (SELECT id FROM `core_stock`  where pk_id=@pkId)  and (status={1} or   count_db=0) ";
            exec(HUtil.s(sql, StockDetailStatus.单据盘亏出库, StockDetailStatus.盘亏中, DetConst.DooTypePk), new { pkId });

            string sql2 = "update core_stock_det set status={0},doi_Type={2},doi_Det_Id=@pkId,create_time=sgj_get_sys_now where pid in (SELECT id FROM `core_stock`  where pk_id=@pkId)   and status={1}";
            exec(HUtil.s(sql2, StockDetailStatus.库存, StockDetailStatus.盘盈, DetConst.DoiTypePy), new { pkId });

            string outStockSql = " update core_stock t set status={0} where PK_ID=@pkId  and NOT EXISTS (select * from core_stock_det d where d.pid=t.id and d.status between  {1} and {2}  )";
            exec(HUtil.s(outStockSql, StockStatus.盘亏删除,StockDetailStatus.下线, StockDetailStatus.上限), new { pkId });
            StatUtil.changeBatch(this,List ); 
            statPkRes(pk.id);
             
            exec(" update core_stock t set PK_ID=0 where PK_ID=@pkId   ", new { pkId });

            exec("update Wh_Dopk set status=" + (int)DoStatus.执行完成 + " where id=@id", pk);
            return new TransRes();
        }


        void statPkRes(long pkId) {

            String sql = @"SELECT  t.item_Id ,t.batch_No,sum(CASE when t.doi_Det_Id<>@pkId then t.count_db else 0  end ) old, 
                         sum( CASE when t.status={0} then t.count_db else 0  end ) now
                        FROM core_stock_det t join core_stock s where s.pk_id=@pkId   group by t.item_Id,t.batch_No";

            sql = HUtil.s(sql, StockDetailStatus.库存);
            List<WhDopkRes> resList = query<WhDopkRes>(sql, new { pkId });
            foreach (WhDopkRes res in resList) {
                res.pkId = pkId;
            }
            if (resList.Count > 0) {
                batchInsert(resList);
            }

        }



    }
}
